package serlvet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器给信件，下次来带信件
        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");


        PrintWriter out = resp.getWriter();
//        服务器从客户端获取，
        Cookie[] cookies = req.getCookies();//cookie可能存在多个，返回的数组
        if (cookies != null) {
            out.write("上次访问的时间是：");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("createTime")) {
//                    获取cookie值
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }
            }
        } else {
            out.write("第一次登陆");
        }
        Cookie createTime = new Cookie("createTime", System.currentTimeMillis() + "");
        createTime.setMaxAge(24 * 60 * 60);//有效期为1天
        createTime.setMaxAge(0);//立马删除

        resp.addCookie(createTime);//相应给客户端

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
